﻿# -*-coding:utf-8-*-
import os
import shutil
from time import sleep
from retrying import retry
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import send_email
from Logs.log import log1
from utils import wait_time, EIP_username, EIP_password, EIP_url, save_zip_files, save_csv_files, update_po, e0, e1, e2, s0, s2, s3, select_result, pro_files


class fileExport:
    def __init__(self, path):
        self.url = EIP_url
        self.save_address = path
        # 修改浏览器下载路径
        chromeOptions = webdriver.ChromeOptions()
        prefs = {"download.default_directory": self.save_address}
        chromeOptions.add_experimental_option("prefs", prefs)
        chromeOptions.add_argument('--no-sandbox')
        self.dr = webdriver.Chrome(chrome_options=chromeOptions)

    @retry(stop_max_attempt_number=3)
    def parse_url(self):
        self.dr.set_page_load_timeout(60)
        self.dr.maximize_window()
        self.dr.get(self.url)

    def login(self):
        username = WebDriverWait(self.dr, wait_time).until(lambda driver: self.dr.find_element_by_id("txtUserName"))
        pwd = WebDriverWait(self.dr, wait_time).until(lambda driver: self.dr.find_element_by_id("txtPassword"))
        username.send_keys(EIP_username)
        pwd.send_keys(EIP_password)
        WebDriverWait(self.dr, wait_time).until(EC.element_to_be_clickable((By.ID, "btnLogin"))).click()

    def enter_export(self, po_line):
        # 点击Report
        WebDriverWait(self.dr, wait_time).until(
            EC.element_to_be_clickable((By.XPATH, "//span[@title='REPORT']"))).click()
        # 点击MES_REPORT(SZ)
        WebDriverWait(self.dr, wait_time).until(
            EC.element_to_be_clickable((By.XPATH, "//div[text()='MES_REPORT(SZ)']/following-sibling::div[1]"))).click()
        # 点击罗技数据导出
        WebDriverWait(self.dr, wait_time).until(
            EC.element_to_be_clickable((By.XPATH, "//span[text()='罗技数据导出']"))).click()
        # 切换到iframe标签
        f = WebDriverWait(self.dr, wait_time).until(
            lambda driver: self.dr.find_elements_by_xpath("//div[@class='tabs-panels tabs-panels-noborder']//iframe"))
        self.dr.switch_to.frame(f[1])
        # 选择MASTER文件类型
        WebDriverWait(self.dr, wait_time).until(
            EC.element_to_be_clickable((By.XPATH, "//*[@id='tableTool']/span[4]/span/a"))).click()
        WebDriverWait(self.dr, wait_time).until(EC.element_to_be_clickable((By.ID, "_easyui_combobox_i2_0"))).click()
        sleep(2)
        # 输入PO,行号
        po_num = po_line.split("-")[0]
        line_num = po_line.split("-")[1]
        po = WebDriverWait(self.dr, wait_time).until(
            lambda driver: self.dr.find_element_by_id("_easyui_textbox_input1"))
        line = WebDriverWait(self.dr, wait_time).until(
            lambda driver: self.dr.find_element_by_id("_easyui_textbox_input2"))
        po.send_keys(po_num)
        line.send_keys(line_num)
        # 导出
        self.click_export()
        sleep(30)
        # 导出TXN文件
        # 选择TXN文件类型
        WebDriverWait(self.dr, wait_time).until(
            EC.element_to_be_clickable((By.XPATH, "//*[@id='tableTool']/span[4]/span/a"))).click()
        WebDriverWait(self.dr, wait_time).until(EC.element_to_be_clickable((By.ID, "_easyui_combobox_i2_1"))).click()
        self.click_export()
        sleep(30)

    def click_export(self):
        # 点击导出ZIP, 保存本地ZIP_files
        # self.dr.find_element_by_id("exportZIP").click()
        # 点击导出CSV
        self.dr.find_element_by_id("export").click()

    def run(self, po_line):
        # 请求
        try:
            self.parse_url()
        except:
            log1.error("{}导出失败:EIP网页{}请求失败".format(po_line, self.url))
            update_po(e0, "EIP访问失败，请重试!", po_line)
            self.dr.quit()
            return
        # 登录
        try:
            self.login()
        except:
            log1.error("{}导出失败:EIP登录失败".format(po_line))
            update_po(e0, "EIP登录失败，请重试!", po_line)
            self.dr.quit()
            return
        # 导出
        try:
            self.enter_export(po_line)
        except Exception as e:
            log1.error("{}导出失败:{}".format(po_line, e))
            update_po(e0, "EIP无此PO号导出文件/导出异常，请重试!", po_line)
        self.dr.quit()


def run(datas):
    if not datas:
        # log1.info("无上传的po")
        return True
    log1.info("上传的po有:{}".format(datas))
    save_address = save_zip_files  # ZIP格式
    # save_address = save_csv_files  # CSV格式
    try:
        os.makedirs(save_address)
    except:
        shutil.rmtree(save_address)
        os.makedirs(save_address)
    for po_line in datas:
        result_dict = select_result(po_line)
        upload_status = result_dict[2]
        if (not upload_status) or (upload_status in [e0, e1]):
            # 新建保存的目录
            path = os.path.join(save_address, po_line)
            try:
                os.makedirs(path)
            except:
                pass
            ex = fileExport(path)
            ex.run(po_line)
            # 发送邮件
            try:
                send_email.run([po_line])
                log1.info("{}导出(发送邮件)OK!".format(po_line))
            except:
                log1.error("发送邮件失败!")
        elif upload_status in [e2, s0, s2, s3]:
            pro_file = os.path.join(pro_files, po_line)
            try:
                shutil.move(pro_file, save_address)
            except:
                try:
                    old_file = os.path.join(save_address, po_line)
                    shutil.rmtree(old_file)
                    shutil.move(pro_file, save_address)
                except:
                    update_po(e0, "文件操作异常,等待下次自动运行", po_line)
                    log1.error("process_file无{}文件".format(po_line))

